package com.gogowan.agroenterprise.newview;

import java.util.ArrayList;
import java.util.List;

import com.gogowan.agroenterprise.MyApplication;
import com.gogowan.agroenterprise.R;
import com.gogowan.agroenterprise.barcode.Intents;
import com.gogowan.agroenterprise.base.BaseActivity;
import com.gogowan.agroenterprise.contorl.MyAsyncTask;
import com.gogowan.agroenterprise.db.DBHelper;
import com.gogowan.agroenterprise.model.CollectCode;
import com.gogowan.agroenterprise.model.CollectCodeRequest;
import com.gogowan.agroenterprise.model.CollectData;
import com.gogowan.agroenterprise.model.GetbaseInfoRequest;
import com.gogowan.agroenterprise.model.GetbaseInfoResult;
import com.gogowan.agroenterprise.model.LoginResultInfo;
import com.gogowan.agroenterprise.model.ResultInfo;
import com.gogowan.agroenterprise.newview.NewCollectSelect.DataSyncTask;
import com.gogowan.agroenterprise.utils.Utils;
import com.gogowan.agroenterprise.widget.adapter.CollectScanAdapter;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class NewCollectScan extends BaseActivity implements OnClickListener {

	private TextView collectTime;
	private EditText collectMan;
	private ImageButton fhBtn;
	
	// 总的list
	private ArrayList<String> codeStringList = new ArrayList<String>();
	private List<String> tempList = new ArrayList<>();
	// 扫码返回的list
	private ArrayList<String> resultStringList;
	private String resultStr = "";
	private Button btnScan;
	private Button btnHWScan;
	private Button btnCancel;
	private Button btnOK;
	private List<CollectData> datas = new ArrayList<>();
	private CollectScanAdapter collectScanAdapter;
	private ListView listView;
	private DBHelper dbHelper;
	private ProgressDialog progressDialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_collect_scan);
		initView();
	}

	private void initView() {
		dbHelper = new DBHelper(this);
		dbHelper.openDatabase();
		// 查询本地所有扫码记录
		codeStringList.addAll(dbHelper.getScanList());
		fhBtn = (ImageButton) findViewById(R.id.in_storage_fh_btn);
		fhBtn.setOnClickListener(this);
		SharedPreferences preferences = getSharedPreferences("LoginINfo", MODE_PRIVATE);
		
		
		collectTime = (TextView) findViewById(R.id.collect_time);
		collectMan = (EditText) findViewById(R.id.collect_man);
		collectTime.setText(Utils.getCurrentTime());
		collectMan.setText(MyApplication.mSettings.getString("username",""));

		btnScan = (Button) findViewById(R.id.btnScan);
		btnHWScan = (Button) findViewById(R.id.btnScanHw);
		btnCancel = (Button) findViewById(R.id.btnCancel);
		btnOK = (Button) findViewById(R.id.btnOk);
		btnScan.setOnClickListener(this);
		btnHWScan.setOnClickListener(this);
		btnCancel.setOnClickListener(this);
		btnOK.setOnClickListener(this);

		listView = (ListView) findViewById(R.id.xmlist);
		collectScanAdapter = new CollectScanAdapter(datas, this);
		listView.setAdapter(collectScanAdapter);
	}

	@Override
	public void onClick(View v) {
		Intent intent;
		switch (v.getId()) {
		case R.id.btnScan:
			intent = new Intent(Intents.Scan.ACTION);
			intent.putExtra(Intents.Scan.IS_BULT_MODE, true);
			intent.putStringArrayListExtra("scans", codeStringList);
			startActivityForResult(intent, 40);
			break;
		case R.id.btnScanHw:
			intent = new Intent(NewCollectScan.this, HWDialogActivity.class);
			intent.putExtra("type", "lx");
			intent.putStringArrayListExtra("scans", codeStringList);
			this.startActivityForResult(intent, 505);
			break;
		case R.id.in_storage_fh_btn:
			showCancelDialog();
			break;
		case R.id.btnCancel:
			showCancelDialog();
			break;
		case R.id.btnOk:
			if (datas.size() <= 0) {
				Toast.makeText(getApplicationContext(), "请先扫码采集", Toast.LENGTH_SHORT).show();
				return;
			}

			if (Utils.getNetworkType(this) == 0) {
				dbHelper.insertScanData(datas, collectTime.getText().toString());
				Toast.makeText(getApplicationContext(), "缓存本地成功", Toast.LENGTH_SHORT).show();
				finish();
				return;
			}

			CollectCodeRequest codeRequest = new CollectCodeRequest();
//			codeRequest.setEnterpriseId(String.valueOf(loginResultInfo.getEnterpriseinfo().getEnterpriseid()));
			CollectCode collectCode = new CollectCode();
//			collectCode.setCollectUserId(MyApplication.mSettings.getString("personid",""));
//			collectCode.setCollectUserName(String.valueOf(MyApplication.mSettings.getString("username","")));
			collectCode.setCollectTime(collectTime.getText().toString());
			collectCode.setCode(datas);
			List<CollectCode> list = new ArrayList<>();
			list.add(collectCode);
			codeRequest.setCodeInfo(list);
			DataUploadTask dataSyncTask = new DataUploadTask();
			progressDialog = ProgressDialog.show(this, getString(R.string.alert_title), "正在提交信息,请稍候....", true, false);
			dataSyncTask.execute(codeRequest);
			break;
		default:
			break;
		}
	}

	private void showCancelDialog() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("系统提示");
		builder.setMessage("确定要退出采集页面吗？\n退出后采集记录将会丢失！");
		builder.setPositiveButton("确定退出", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				finish();
			}
		});
		builder.setNegativeButton("取 消", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.cancel();
			}
		});
		builder.create().show();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK) {
			switch (requestCode) {
			case 40:
			case 505:
				// 标签采集
				resultStringList = data.getStringArrayListExtra(Intents.Scan.RESULTLIST);
				if (resultStringList == null || resultStringList.size() == 0) {
					return;
				}
				for (int i=0;i<resultStringList.size();i++){
					String result = resultStringList.get(i);
					result=result.replaceAll("\n","");
					String[] parts = result.split("MA.156.M0");
					if (parts.length >= 3) {//"包含2个\"MA.156.M0\""
						//
						for (int j = 0; j < parts.length; j++) {
							if (j==1){
								if (!resultStringList.contains("MA.156.M0"+parts[1])) {
									resultStringList.set(i, "MA.156.M0" + parts[1]);
								}
							}else if(j>1){
								if (!resultStringList.contains("MA.156.M0"+parts[j])) {
									resultStringList.add(i + j + 1 - 2, "MA.156.M0" + parts[j]);
								}
							}
						}
					}

				}

				queryDetails(resultStringList);
				break;
			default:
				break;
			}
		}
	}

	// 查询本地信息
	private void queryDetails(ArrayList<String> list) {
		tempList.clear();
		for (String str : list) {
			CollectData bean = null;
			if (TextUtils.isEmpty(str)) {
				continue;
			}
			// 必须网址且可按=拆分
			if (str.startsWith("http") && str.split("=").length == 2) {
				// 获取码号
				String temp = str.split("=")[1];
				// 产品码可按/拆分
				if (temp.split("/").length == 3) {
					String[] arrs = temp.split("/");
					// 尾号是.2.3.8可被采集
					if (temp.endsWith(".2") || temp.endsWith(".3") || temp.endsWith(".8")) {
						bean = dbHelper.getResultData(arrs[0] + "/" + arrs[1] + "/", 0);
					}
				} else if (TextUtils.isDigitsOnly(temp) && temp.length() == 32) {
					// 农药码
					bean = dbHelper.getResultData(temp.substring(11, 17), 1);
				}else if (!(temp.contains("/"))&& temp.length()!=32){
					// 简码
					bean = dbHelper.getResultData(temp.substring(0,7), 2);
				}
				if (bean != null) {
					bean.setMaterialCode(str);
					bean.setMaterialScode(temp);
					bean.setCodeStr(temp);
					bean.setScanTime(Utils.getCurrentTime());
					bean.setOperMan(collectMan.getText().toString());
					bean.setCollectUserId(MyApplication.mSettings.getLong("personid",0)+"");
					bean.setOrderTime(collectTime.getText().toString());
					bean.setCollectUserId(MyApplication.mSettings.getLong("personid",0)+"");
					codeStringList.add(str);
					tempList.add(str);
					datas.add(bean);
				}
			}
		}
		if (tempList.size() <= 0) {
			Toast.makeText(getApplicationContext(), "未查到该批码信息", Toast.LENGTH_SHORT).show();
		}
		collectScanAdapter.notifyDataSetChanged();
	}

	// 数据采集上传
	class DataUploadTask extends MyAsyncTask {

		@Override
		protected Object doInBackground(Object... params) {
			CollectCodeRequest collectCodeRequest = (CollectCodeRequest) params[0];
			String json = Utils.toJSON(collectCodeRequest);
			com.gogowan.agroenterprise.model.Message message = new com.gogowan.agroenterprise.model.Message(32000, true,
					json);
			String res = Utils.postCommit(getString(R.string.first_url) + getString(R.string.first_url_page), message);
			return res;
		}

		@Override
		protected void onPostExecute(Object res) {
			if (isFinishing()) {
				return;
			}
			progressDialog.cancel();
			try {
				if (res == null || res.equals("")) {
					initMsg(getString(R.string.server_error), true);
				} else {
					com.gogowan.agroenterprise.model.Message message = (com.gogowan.agroenterprise.model.Message) Utils
							.fromJSON((String) res, com.gogowan.agroenterprise.model.Message.class);
					String string = Utils.getMessageContent(message);

					if (string == null || string.equals("")) {
						initMsg(getString(R.string.analyse_error), true);
					} else {
						ResultInfo resultInfo = (ResultInfo) Utils.fromJSON(string, ResultInfo.class);
						if (resultInfo.getResult() == 32000) {
							// 成功
							initMsg(resultInfo.getResultinfo(), false);
						} else if (resultInfo.getResult() == -32000) {
							// -32000返回值不用缓存数据
							initMsg(resultInfo.getResultinfo(), false);
						} else {
							// 其他异常缓存数据
							initMsg(resultInfo.getResultinfo(), true);
						}
					}
				}
			} catch (Exception ex) {
				initMsg(getString(R.string.analyse_error), true);
			}
			super.onPostExecute(res);
		}
	}

	private void initMsg(String msg, boolean save) {
		Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
		if (save) {
			dbHelper.insertScanData(datas, collectTime.getText().toString());
		}
		finish();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
			showCancelDialog();
		}
		return super.onKeyDown(keyCode, event);
	}

}
